package com.alibaba.csp.sentinel.dashboard.rule.convert;


import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.*;
import com.alibaba.csp.sentinel.dashboard.discovery.AppInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * @author: shaozeming
 * @date: 2022/8/8 15:58
 * @description:
 **/
public class Converter {

    private static final String EMPTY_List= "[]";

    public static  String encode(List<RuleEntity> rule) {
        if (rule == null || rule.size() == 0) {
            return EMPTY_List;
        }
        RuleConverter converter = getConverter(rule.get(0).getClass());
        if(null== converter){
            return null;
        }
        return converter.ruleEntityEncoder().convert(rule);

    }

    public static  List<RuleEntity> decode(AppInfo appInfo,String rule, Class clz) {
        if (rule == null || rule.length() == 0) {
            return new ArrayList<>();
        }
        RuleConverter converter = getConverter(clz);
        if(null== converter){
            return null;
        }
        return converter.ruleEntityDecoder(appInfo).convert(rule);

    }

    public static <T extends RuleEntity> RuleConverter getConverter(Class<T> clz) {
        if (clz.equals(AuthorityRuleEntity.class) ) {
           return   new AuthorityRuleConverter();
        } else if (clz.equals(DegradeRuleEntity.class)) {
            return   new DegradeRuleConverter();
        } else if (clz.equals(FlowRuleEntity.class) ) {
            return   new FlowRuleConverter();
        } else if(clz.equals(ParamFlowRuleEntity.class) ) {
            return   new ParamFlowConverter();
        } else if (clz.equals(SystemRuleEntity.class) ) {
            return   new SystemConverter();
        }else if (clz.equals(GatewayFlowRuleEntity.class) ) {
            return   new GetawayRuleConverter();
        }else if (clz.equals(GroupRuleEntity.class) ) {
            return   new GroupRuleConverter();
        }else if (clz.equals(ApiDefinitionEntity.class) ) {
            return   new GatewayApiConverter();
        }
        return null ;

    }


}
